<template>
  <div class="page accountStatement-list padding-safe-area-bottom">
    <messageComfirm @leftCallBack="cancel" @rightCallBack="sure" :visible="modalVisible">
      <div class="send-email">
        <div class="title">邮箱</div>
        <input type="email" v-model="email" placeholder="@" />
      </div>
    </messageComfirm>
    <filterItem
      ref="filterItem"
      @filterChoice="handleFilterChoice"
      :payType="payTypeList"
      :defaultDate=[defaultStartDate,defaultEndDate]
      :roleInfo="roleInfo"
      :tabType="tabType"
    ></filterItem>
    <!-- 对账单详情 -->
    <billDetails ref="billDetails" :param="detailParam" :billData="billData"></billDetails>
    <!-- 门店账单按日期查看列表 -->
    <mdAccount ref="mdAccount" :param="mdParam" :overviewData="currentOverview" @linkToDetail="linkToMdDetail"></mdAccount>
    <div class="scroll-view">
      <customHeader middleTitle="分账对账单" @rightCallBack="handleClickFilter" @leftCallBack="goBack">
        <i class="zhk-nav_filter"></i>
      </customHeader>
      <div class="notice">
        <i class="zhk-bf-svg"></i>
        <span>暂不统计银联刷卡以及当面付业务手续费及清算金额</span>
      </div>
      <div class="date-text">
        <!-- <i class="zhk-activity_rl"></i> -->
        <span>{{formatDate(startTime)}} 至 {{formatDate(endTime)}}</span>
      </div>
      <ul class="control-tab" v-show="tabNav.length">
        <li v-for="(item,index) in tabNav" :key="index"
          :class="{active:tabIndex===index}"
          @click="tabClick(item.type, index)"
        >{{item.name}}</li>
      </ul>
      <div class="page-body">
        <ul class="tab-container">
          <!-- 总览 -->
          <li :class="{hide: tabType!=='overview'}">
            <no-data msg="暂无数据" v-if="!hasTotal"></no-data>
            <div class="overview-header" v-if="hasTotal" @click="linkToDetail('OverViewDetail','对账单总览', overviewData, true)">
              <div class="tc">结算合计(元)<i class="zhk-list_rarrow"></i></div>
              <div class="overview-header_total tc">
                <!-- <span>{{overviewData.liquidationAmount||"0.00"}}</span> -->
                <span>{{CommonUtil.moneyFormate(overviewData.actualTotalAmount)}}</span>
              </div>
              <div class="overview-header_flex">
                <div class="overview-header_flex-item">
                  <p>收款笔数</p>
                  <p>
                    <span>{{overviewData.tradeNumber || 0}}</span>
                  </p>
                </div>
                <div class="overview-header_flex-item">
                  <p>退款笔数</p>
                  <p>
                    <span>{{overviewData.refundsNumber || 0}}</span>
                  </p>
                </div>
              </div>
            </div>
            <div v-if="hasTotal&&overViewList&&overViewList.length">
              <p class="list-title">按日查看</p>
              <ul class="date-list">
                <li v-for="(item,index) in overViewList" :key="index"  @click="linkToDetail('OverViewDetail','对账单总览', item)">
                      <span class="title">{{item.bizDate}}</span>
                      <div>
                        <span class="amount">{{CommonUtil.moneyFormate(item.actualTotalAmount)}}元</span>
                        <div class="bs">收款{{item.tradeNumber}}笔 退款{{item.refundsNumber}}笔</div>
                      </div>
                      <i class="zhk-list_rarrow"></i>
                </li>
              </ul>
            </div>
          </li>
          <!-- 按区域查看 -->
          <li :class="{hide:tabType!=='area'}">
            <no-data msg="暂无数据" v-if="areaList&&!areaList.length"></no-data>
            <div v-if="areaList&&areaList.length">
              <ul class="date-list mt20">
                <li v-for="(item,index) in areaList" :key="index" @click="linkToMd(item)">
                  <span class="title">{{item.name}}</span>
                  <div>
                    {{CommonUtil.moneyFormate(item.actualTotalAmount)}}元
                  </div>
                  <i class="zhk-list_rarrow"></i>
                </li>
              </ul>
            </div>
          </li>
          <!-- 按门店查看 -->
          <li :class="{hide:tabType!=='shop'}">
            <no-data msg="暂无数据" v-if="!hasShop"></no-data>
            <ul class="date-list mt20" v-else>
              <li v-for="(item,index) in listShop" :key="index"  @click="linkToMd(item, true)">
                    <span class="title text-overflow-2">{{item.shopName}}</span>
                    <div>
                      <span class="amount">{{CommonUtil.moneyFormate(item.actualTotalAmount)}}元</span>
                    </div>
                    <i class="zhk-list_rarrow"></i>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <!-- <div class="btn" @click="sendEmail">发送对账单至邮箱</div> -->
    </div>
  </div>
</template>

<script>
import customHeader from "../../components/header/header";
import messageComfirm from "../../components/messageComfirm/messageComfirm";
import noData from "../../components/noData/noData";
import filterItem from "./filterItem";
import billDetails from "./details";
import mdAccount from './mdAccount';
import { Toast, MessageBox } from "mint-ui";
import moment from "moment";
import jsBridge from "../../tools/jsBridge.js";
import jsAuthority from "../../tools/jsAuthority.js";

export default {
  name: "accountStatement",
  data() {
    return {
      CommonUtil:CommonUtil,
      joinMarketing:1,//是否开通营销 1:开通过 0:未开通
      areaList: null,  //区域列表
      tabType: 'overview',
      currentOverview: {},
      expand: false,
      mdParam: {},
      detailParam: {},
      tabNav: [],
      tabIndex: 0,
      email: "",
      modalVisible: false,
      filterData: {
        startDate: null,
        endDate: null,
        payType: [],
        store: []
      },
      defaultLoadData: [],
      payTypeList: [],
      overviewData: null, //要循环展示的门店总览对账信息
      listShop: [],
      //isExhibition: false, //判断银联POS机的提示语
      hasTotal: false,
      hasShop: false,
      roleInfo: {
        role: "",
        shopName: "",
        yzShopId: ""
      },
      overViewList: [],  //账单总览，按日查看列表
      billData: {}       //
    };
  },
  methods: {
    goBack() {
      if (this.$refs.billDetails.popupVisible) {
        this.$refs.billDetails.popupHide();
      } else if (this.$refs.filterItem.popupVisible) {
        this.$refs.filterItem.back();
      } else if (this.$refs.mdAccount.popupVisible) {
        this.$refs.mdAccount.popupHide();
      }
      else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    //获取门店、支付方式、时间值的公共方法
    queryEffective() {

      let params = {
        startDate: this.getStartTimestamp(this.filterData.startDate),
        endDate: this.getEndTimestamp(this.filterData.endDate),
        payTypes: [],
        shopIds: []
      };
      //获取支付方式类型
      params.payTypes = new Array();
      for (var i = 0; i < this.filterData.payType.length; i++) {
        if(this.filterData.payType[i].checked){
          params.payTypes.push(this.filterData.payType[i].value);
        }
      }
      //获取门店Id
      params.shopIds = new Array();
      for (var i = 0; i < this.filterData.store.length; i++) {
        params.shopIds.push(this.filterData.store[i].selectKey);
      }
      return params;
    },
    //查询对账单条数
    queryCount() {
      let params = this.queryEffective();
      this.ajax({
        url: "/newapp/reconciliation/queryduizhangNum.do",
        type: "post",
        data: params,
        controlLoading: false,
      })
        .then(res => {
          if (res.success) {
            if (res.resultObject <= 0) {
              MessageBox({
                title: "提示",
                message:
                  "当前条件下无账单数据，无法生成账单文件，请更换条件查询",
                showCancelButton: false,
                confirmButtonText: "知道了"
              });
            } else {
              this.modalVisible = true;
            }
          }else{
            Toast(res.msg);
          }
        })
        .catch(function (err) {

        });
    },
    //查询支付方式
    PaymentMethod() {
      this.ajax({
        url: "/newapp/reconciliation/getPayType.do",
        type: "get",
        controlLoading: false,
        data: {}
      })
        .then(res => {
          if (res.success) {
            let datas = res.resultObject;
            let payTypeList=[];
            for (var i = 0; i < datas.length; i++) {
              if (datas[i] == 2) {
                payTypeList.push({
                  label: "支付宝",
                  value: datas[i],
                  checked: true
                });
              }
              if (datas[i] == 7) {
                payTypeList.push({
                  label: "云闪付",
                  value: datas[i],
                  checked: true
                });
              }
              if (datas[i] == 5) {
                payTypeList.push({
                  label: "微信",
                  value: datas[i],
                  checked: true
                });
              }
              if (datas[i] == 4) {
                payTypeList.push({
                  label: "POS刷卡",
                  value: datas[i],
                  checked: true
                });
                //this.isExhibition = true;
              }
               if (datas[i] == 8) {
                payTypeList.push({
                  label: "余额支付",
                  value: datas[i],
                  checked: true
                });
              }
              if (datas[i] == 1) {
                //当商户账号开通时，默认就开通了现金收款，所以不参与过滤
                payTypeList.push({
                  label: "现金",
                  value: 1,
                  checked: false
                });
              }
            }
            payTypeList.push(payTypeList.shift()); //把第一位的现金移到最后
            this.payTypeList= payTypeList;
            this.filterData.payType = payTypeList;

            //根据角色判断，店长直接拿门店信息，不请求门店列表
            if (this.roleInfo.manyShopFlag!==undefined&&!this.roleInfo.manyShopFlag) {
              this.filterData.store = [
                {
                  selectName: this.roleInfo.shopName,
                  selectKey: this.roleInfo.yzShopId
                }
              ];

              this.selectOverView();
            } else {
              this.allShopId(); //所有门店的接口
            }
          }
        })
        .catch(function (err) {

        });
    },
    //查询所有门店的接口
    allShopId() {
      this.ajax({
        url: "/newapp/reconciliation/getAllShop.do",
        type: "get",
        controlLoading: false,
      })
        .then(res => {
          if (res.success) {
            this.ShopListIdAndName(res.resultObject);
            this.selectOverView();
          }
        })
        .catch(function (err) {

        });
    },
    //门店封装数据
    ShopListIdAndName(result) {
      for (let i = 0; i < result.length; i++) {
        this.filterData.store.push({
          selectName: result[i].shopName,
          selectKey: result[i].shopId
        });
      }
    },
    //查询对账单总览的数据源
    selectOverView() {
      let params = this.queryEffective();
      this.ajax({
        url: "/newapp/reconciliation/overViewNew.do",
        type: "post",
        controlLoading: true,
        data: params
      }).then(result => {
        if (result.success) {
          let data = result.resultObject;
          this.overviewData = data;
          if (data) {
            this.hasTotal = true;
          } else {
            this.hasTotal = false;
          }
          if(result.resultObject) {
            let overViewList = result.resultObject.summaryBizDateList || [];
            overViewList.forEach(item=> {
              item.bizDate = (item.bizDate+'').replace(/([\d]{4})([\d]{2})(\d*)/,'$1-$2-$3');
              item.startDate = moment(item.bizDate).valueOf();
              item.endDate = moment(item.bizDate).add(1, 'd').valueOf();
            });
            this.overViewList = overViewList;
          }
        } else {
          Toast(result.msg);
        }
      }).catch(function (err) {

      });
    },
    //按门店总览的数据源查询
    selectShopView() {
      let params = this.queryEffective();
      this.ajax({
        // url: "/app/reconciliation/shopShow.do",
        url: 'newapp/reconciliation/queryAntStatementShopSummeryList.do',
        type: "post",
        controlLoading: true,
        data: params
      }).then(result => {
        if (result.success) {
          let data = result.resultObject || [];
          this.listShop = data;
          this.hasShop = !!data.length;
        }else {
          Toast(result.msg);
        }
      }).catch(err=> {

      });
    },
    //获得开始时间的时间戳
    getStartTimestamp(param) {
      //转换成世界时间，格式为：yyyymmdd 00:00:00
      let date = window.DateUtil.getDateFormat2(new Date(param));
      let time = Math.round(new Date(date).getTime());
      return time;
    },
    //获得结束时间的时间戳
    getEndTimestamp(param) {
      //服务端对结束时间的判断是小于，所以取世界时间对后加+1天
      let date = window.DateUtil.getDateFormat2(new Date(param));
      let time = new Date(date).getTime() + 24 * 60 * 60 * 1000;
      return time;
    },
    //打开筛选
    handleClickFilter() {
      this.$refs.filterItem.popupShow();
    },
    //筛选确定
    handleFilterChoice(v) {
      const store = this.filterData.store;
      this.filterData = v;
      if (v.store.length === 0) {
        this.filterData.store = store;
      }
      // if (this.tabIndex == 0) {
      //   this.selectOverView();
      // } else {
      //   this.selectShopView();
      // }
      this.tabClick(this.tabType, this.tabIndex);
    },
    //tab切换
    tabClick(type, index) {
      this.tabIndex = index;
      this.tabType = type;
      const func = {
        'overview': this.selectOverView,
        'area': this.getAreaList,
        'shop': this.selectShopView
      }
      func[type] && func[type]();
      // if (index == 0) {
      //   this.selectOverView();
      // } else {
      //   this.selectShopView();
      // }
    },
    getAreaList() {
      let params = this.queryEffective();
      this.ajax({
        url: "/newapp/reconciliation/reginOverView.do",
        type: "post",
        controlLoading: true,
        data: params
      }).then(result => {
        if(result.success) {
          let _list = [];
          let data = result.resultObject || {};
          if(data) {
            Object.keys(data).forEach(key=> {
              let [reginId, name] = key.split('_');
              data[key].name = name;
              data[key].reginId = reginId;
              data[key].shopId = params.shopIds;
              reginId && _list.push(data[key]);
            })
          }
          this.areaList = _list;
        }else {
          Toast(result.msg);
        }
      }).catch(function (err) {

      });
    },
    //打开发送邮箱弹窗
    sendEmail() {
      this.queryCount();
    },
    //关闭邮箱弹窗
    cancel() {
      this.modalVisible = false;
    },
    //邮箱发送确定
    sure() {
      if (!this.email) {
        Toast("邮箱地址不能为空");
        return;
      }
      const reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (!reg.test(this.email)) {
        Toast("邮箱地址格式有误，请重新输入");
        return;
      }
      let params = this.queryEffective();
      params.email = this.email;
      //对账单发送邮箱
      this.ajax({
        url: "/newapp/reconciliation/SendMailbox.do",
        type: "post",
        data: params
      })
        .then( (res)=> {
          if (res.success) {
            this.modalVisible = false;
            this.$router.push({
              path: "/accountStatement/sendSuccess",
              query: { email: this.email }
            });
          }else{
            Toast(res.msg);
          }
        })
        .catch(function (err) {

        });
    },
    //门店按日期查看列表跳转详情
    linkToMdDetail(params, data, flag) {
      this.billData = data;
      this.detailParam = params;
      if(flag) {
        this.billData.startDate = params.startDate;
        this.billData.endDate = params.endDate;
        this.billData.type = 'overview';
      }
      this.billData.joinMarketing=this.joinMarketing;
      this.$refs.billDetails.popupShow();
    },
    //门店跳转详情
    linkToDetail(shopId, shopName, item, flag) {
      let params = this.queryEffective();
      let shopIds = [];
      if (shopId == "OverViewDetail") {
        shopIds = params.shopIds;
      } else {
        shopIds.push(shopId);
      }
      this.detailParam = {
        shopIds: shopIds,
        shopName: shopName,
        startDate: params.startDate,
        endDate: params.endDate,
        payTypes: params.payTypes
      };
      if(item && item.startDate) {
        this.detailParam.startDate = item.startDate;
        this.detailParam.endDate = item.endDate;
      }
      this.billData = item;
      this.billData.joinMarketing=this.joinMarketing;
      if(flag) {
        this.billData.startDate = params.startDate;
        this.billData.endDate = params.endDate;
        this.billData.type = 'overview';
      }
      this.$refs.billDetails.popupShow();
    },
    //跳转门店账单预览
    linkToMd(item, flag) {
      let params = this.queryEffective();
      this.mdParam = {
        shopIds: flag ? [item.shopId] : item.shopId,
        shopName: item.shopName || item.name,
        startDate: params.startDate,
        endDate: params.endDate,
        payTypes: params.payTypes
      };
      this.currentOverview = item;
      this.$refs.mdAccount.popupShow();
    },
    formatDate(date) {
      return String(date).replace(/\//g, "-");
    },
    //是否开通营销 1:开通过 0:未开通
    getMarketingStatus() {
      this.ajax({
        url: "/newapp/reconciliation/getMarketingStatus.do",
        type: "get",
        controlLoading: false,
      }).then(result => {
        if(result.success) {
          this.joinMarketing=result.resultObject;
        }else {
          Toast(result.msg);
        }
      }).catch(function (err) {

      });
    },
  },
  watch: {
    //检测属性变化defaultLoadData
    defaultLoadData: function (newValue, oldValue) {
      if (newValue !== oldValue) {
        let loadData = this.defaultLoadData;
        if (loadData.length == 2) {
          if (loadData[0] == "haveStartDate" && loadData[1] == "haveEndDate") {
            this.selectOverView();
          }
        }
      }
    }
  },
  computed: {
    defaultStartDate() {
      //const hour = new Date().getHours();
      // if (hour < 13) {
      //   return new Date(new Date() - 2 * 24 * 60 * 60 * 1000);
      // } else {
      //   return new Date(new Date() - 1 * 24 * 60 * 60 * 1000);
      // }
      return new Date(new Date() - 7 * 24 * 60 * 60 * 1000);
    },
    defaultEndDate() {
      //const hour = new Date().getHours();
      // if (hour < 13) {
      //   return new Date(new Date() - 2 * 24 * 60 * 60 * 1000);
      // } else {
      //   return new Date(new Date() - 1 * 24 * 60 * 60 * 1000);
      // }
     return new Date(new Date() - 1 * 24 * 60 * 60 * 1000);
    },
    startTime() {
      if (this.filterData.startDate) {
        return moment(this.filterData.startDate).format("YYYY/MM/DD");
      } else {
        this.defaultLoadData.push("haveStartDate");
        this.filterData.startDate = moment(this.defaultStartDate).format("YYYY/MM/DD");
        return moment(this.defaultStartDate).format("YYYY/MM/DD");
      }
    },
    endTime() {
      if (this.filterData.endDate) {
        return moment(this.filterData.endDate).format("YYYY/MM/DD");
      } else {
        this.defaultLoadData.push("haveEndDate");
        this.filterData.endDate = moment(this.defaultEndDate).format("YYYY/MM/DD");
        return moment(this.defaultEndDate).format("YYYY/MM/DD");
      }
    }
  },
  components: {
    customHeader,
    messageComfirm,
    filterItem,
    billDetails,
    noData,
    mdAccount
  },
  created() {
    const nav = {
      'scan': {type: 'overview', name: "总览" },
      'region': {type: 'area', name: "按区域"},
      'shop': {type: 'shop', name: "按门店"},
    }
    jsAuthority.checkedSuccess(()=> {
      // let shop = jsAuthority.checked(
      //   'app.duizhangdan.query.shop'
      // );
      // let region = jsAuthority.checked(
      //   'app.duizhangdan.query.region'
      // );
      // let scan = jsAuthority.checked(
      //   'app.duizhangdan.query.scan'
      // );
      Object.keys(nav).forEach(key=> {
        let flag = jsAuthority.checked(
          'app.duizhangdan.query.'+key
        );
        flag && this.tabNav.push(nav[key])
      });
    });

    CommonUtil.getUserInfo().then(data => {
      this.roleInfo = data;
      // if(this.roleInfo.role!=4) {
      //   this.tabNav.push({type: 'shop', name: "按门店"})
      // }
      // if(this.roleInfo.role==1) {
      //   this.tabNav.splice(1, 0, {type: 'area', name: "按区域"});
      // }
      this.PaymentMethod(); //判断都有什么支付方式支付方式
    });
    this.getMarketingStatus()
  }
};
</script>

<style lang='scss' scoped>
@import "accountStatement";
</style>
